package com.gss.armory.service;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

import com.gss.armory.domain.BusinessUnitTypeDTO;
import com.gss.armory.domain.CompanyDetailsDTO;
import com.gss.armory.domain.DepartmentDetailsDTO;
import com.gss.armory.domain.DocGeneralDetailsDTO;
import com.gss.armory.domain.DocumentCategoryDTO;
import com.gss.armory.domain.DocumentSubCategory;
import com.gss.armory.domain.DocumentTypeDTO;
import com.gss.armory.domain.DocumentWorkflowDetailsDTO;
import com.gss.armory.domain.DocumentWorkflowDetailsDTO.WorkflowEventStatus;
import com.gss.armory.domain.LocationDetailsDTO;
import com.gss.armory.domain.MasterDetailsForDMSWFDTO;
import com.gss.armory.domain.MasterDetailsForDMSWFDTO.attributes;
import com.gss.armory.form.DepartmentForm;
import com.gss.armory.form.DocumentCategoryForm;
import com.gss.armory.form.LocationForm;
import com.gss.armory.form.SuperFicialRolesMappingForm;
import com.gss.armory.form.UserDetailForm;
import com.gss.armory.persistence.AdminDao;
import com.gss.armory.persistence.CommonDAO;
import com.gss.armory.util.BootUpLoader;
import com.gss.common.util.ApplicationConstants;
import com.gss.common.util.ApplicationMaps;
import com.gss.common.util.ApplicationUtilities;
import com.gss.security.domain.LocationMasterDTO;
import com.gss.security.domain.RoleDetailsDTO;
import com.gss.security.domain.SuperficialRolesMapping;
import com.gss.security.domain.UserDetailsDTO;
import com.gss.security.domain.UserRoleMappingDTO;
import com.gss.security.persistence.AuthenticationDAO;

@Service
public class AdminService {
	@Autowired
	AdminDao adminDao;

	@Autowired
	CommonDAO commonDao;

	 @Autowired
	BootUpLoader bootUpLoader;

	@Autowired
	AuthenticationDAO authenticationDAO;

	private Logger logger = Logger.getLogger(AdminService.class);

	public boolean assignRole(UserRoleMappingDTO detailsDTO) {
		String[] roles = detailsDTO.getRoles();
		logger.debug("ROLES ALLOTED TO USER: " + roles.length);
		UserRoleMappingDTO mappingDTO = new UserRoleMappingDTO();

		boolean resultOfRecordEntry = false;
		boolean resultOfDelete = false;
		List<String> previousRoleList = new ArrayList<String>();
		Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();

		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(UserDetailsDTO.class);
		detachedCriteria
				.add(Restrictions.eq("username", detailsDTO.getUserId()));
		List<UserDetailsDTO> userDetailsDTO = (List<UserDetailsDTO>) commonDao
				.loadAllByCriteria(detachedCriteria);
		authorities = (List<GrantedAuthority>) userDetailsDTO.get(0)
				.getAuthorities();

		for (GrantedAuthority authority : authorities) {
			RoleDetailsDTO detailsDTO1 = (RoleDetailsDTO) authority;
			logger.debug(detailsDTO1.getRoleDesc());
			previousRoleList.add(detailsDTO1.getRoleId());
		}

		for (String roleToDelete : previousRoleList) {
			if (roleToDelete
					.equalsIgnoreCase(ApplicationConstants.DEFAULT_ROLE)) {
				logger.debug("Ignored Role: " + roleToDelete);
				continue;
			}
			logger.debug("Role to delete: " + roleToDelete + "  :for UserId: "
					+ detailsDTO.getUserId());
			mappingDTO.setRoleId(roleToDelete);
			mappingDTO.setUserId(detailsDTO.getUserId());
			resultOfDelete = adminDao.deletePreviousRoles(mappingDTO);
		}

		for (String roleToInsert : roles) {
			logger.debug("Role to insert: " + roleToInsert + "  :for userId: "
					+ detailsDTO.getUserId());
			mappingDTO.setRoleId(roleToInsert);
			mappingDTO.setUserId(detailsDTO.getUserId());
			resultOfRecordEntry = adminDao.updateUser(mappingDTO);
		}

		return resultOfRecordEntry;
	}

	public boolean saveUser(UserDetailForm detailForm) {

		Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
		UserDetailsDTO detailsDTO = new UserDetailsDTO();
		try {
			RoleDetailsDTO roleDetailsDTO = new RoleDetailsDTO();
			roleDetailsDTO.setAuthority(ApplicationConstants.DEFAULT_ROLE);
			authorities.add(roleDetailsDTO);
			detailsDTO.setAuthorities(authorities);

			BeanUtils.copyProperties(detailsDTO, detailForm);
		} catch (IllegalAccessException e) {
			// e.printStackTrace();
			logger.error(e.getMessage(), e);
		} catch (InvocationTargetException e) {
			// e.printStackTrace();
			logger.error(e.getMessage(), e);
		}

		ApplicationUtilities.populateCommonDetails(detailsDTO, true);
		detailsDTO.setAccountNonExpired(true);
		detailsDTO.setAccountNonLocked(true);
		detailsDTO.setCredentialsNonExpired(true);
		detailsDTO.setEnabled(true);

		if (adminDao.saveUser(detailsDTO)) {
			bootUpLoader.loadUserMap();
			return true;
		} else {
			return false;
		}
	}

	public boolean saveLocationMasterDetails(LocationMasterDTO locationMasterDTO) {

		Collection<LocationMasterDTO> collection = ApplicationMaps.LOCATION_DETAILS_MAP
				.values();

		Boolean successFlag = null;

		for (LocationMasterDTO masterDTO : collection) {
			if ((locationMasterDTO.getCity()).equalsIgnoreCase(masterDTO
					.getCity())) {
				successFlag = false;
				return successFlag;
			} else {
				successFlag = true;
			}
		}

		if (adminDao.saveLocationMasterDetails(locationMasterDTO)) {
			bootUpLoader.loadLocationMaster();
			successFlag = true;
		} else {
			successFlag = false;
		}
		return successFlag;
	}

	public boolean saveCompany(CompanyDetailsDTO companyDetailsDTO) {
		boolean successFlag = false;
		boolean alreadyExists = false;
		Collection<CompanyDetailsDTO> collection = ApplicationMaps.COMPANYID_COMPANY_MAP.values();
		
		//checking previous existense of company
		for(CompanyDetailsDTO companyObject : ApplicationMaps.COMPANYID_COMPANY_MAP.values()) {
			if(companyObject.getCdName().equalsIgnoreCase(companyDetailsDTO.getCdName()) 
				|| companyObject.getCdCode().equalsIgnoreCase(companyDetailsDTO.getCdCode())) {

				alreadyExists = true;
			}
		}
		
		//saving company details if it dosen't already exists in db
		if(!alreadyExists) {
			if (adminDao.saveDataInTable(companyDetailsDTO)) {
				bootUpLoader.loadCompany();
				bootUpLoader.loadBusLocs();
				successFlag = true;
			} else {
				successFlag = false;
			}	
		}
		return successFlag;
	}

	public boolean saveLocation(LocationForm locationForm) {

		Collection<LocationDetailsDTO> collection = ApplicationMaps.LOCID_LOC_MAP
				.values();

		Boolean successFlag = null;

		for (LocationDetailsDTO dto : collection) {
			if ((locationForm.getLdName()).equalsIgnoreCase(dto.getLdName())
					|| (locationForm.getLdCode()).equalsIgnoreCase(dto
							.getLdCode())) {
				successFlag = false;
				return successFlag;
			} else {
				successFlag = true;
			}
		}
		logger.debug(locationForm.getLdType());
		LocationDetailsDTO detailsDTO = new LocationDetailsDTO();
		detailsDTO.setLdCode(locationForm.getLdCode());
		detailsDTO.setLdCompanyId(locationForm.getLdCompanyId());
		detailsDTO.setLdName(locationForm.getLdName());
		detailsDTO.setLdType(locationForm.getLdType());
		logger.debug(detailsDTO.getLdType());
		List<DepartmentDetailsDTO> departmentDetailsDTOs = new ArrayList<DepartmentDetailsDTO>();
		Long[] ddId = locationForm.getDdId();
		for (Long id : ddId) {
			DepartmentDetailsDTO detailsDTO2 = ApplicationMaps.DEPARTMENTID_DEPARTMENT_MAP
					.get(id);
			departmentDetailsDTOs.add(detailsDTO2);
		}
		detailsDTO.setDepartmentDetailsDTOs(departmentDetailsDTOs);
		if (adminDao.saveLocation(detailsDTO)) {
			bootUpLoader.loadDepts();
			bootUpLoader.loadBusLocs();
			bootUpLoader.loadCompany();
			successFlag = true;
		} else {
			successFlag = false;
		}
		return successFlag;

	}

	public boolean saveDepartment(DepartmentForm departmentForm) {
		Collection<DepartmentDetailsDTO> collection = ApplicationMaps.DEPARTMENTID_DEPARTMENT_MAP
				.values();

		Boolean successFlag = null;

		for (DepartmentDetailsDTO dto : collection) {
			if ((departmentForm.getDdName()).equalsIgnoreCase(dto.getDdName())
					|| (departmentForm.getDdShortName()).equalsIgnoreCase(dto
							.getDdCode())) {
				successFlag = false;
				return successFlag;
			} else {
				successFlag = true;
			}
		}

		DepartmentDetailsDTO detailsDTO = new DepartmentDetailsDTO();
		detailsDTO.setDdName(departmentForm.getDdName());
		detailsDTO.setDdCode(departmentForm.getDdShortName());
		// detailsDTO.setDetailsDTO(departmentForm.getDetailsDTO());
		if (adminDao.saveDepartment(detailsDTO)) {
			bootUpLoader.loadDepts();
			successFlag = true;
		} else {
			successFlag = false;
		}
		return successFlag;
	}

	public boolean saveUnitType(BusinessUnitTypeDTO unitType) {
		List<String> businessUnitType = ApplicationMaps.BUTYPE_LIST;

		Boolean successFlag = null;

		for (int i = 0; i < businessUnitType.size(); i++) {
			if ((businessUnitType.get(i)).equalsIgnoreCase(unitType
					.getBuTypeName())) {
				successFlag = false;
				return successFlag;
			} else {
				successFlag = true;
			}
		}

		if (adminDao.saveUnitType(unitType)) {
			successFlag = true;
		} else {
			successFlag = false;
		}

		return successFlag;
	}

	public boolean saveDocumentType(DocumentTypeDTO documentTypeDTO) {
		Collection<DocumentTypeDTO> collection = ApplicationMaps.DOCUMENT_TYPE_ID_MAP
				.values();

		Boolean successFlag = null;

		for (DocumentTypeDTO dto : collection) {
			if ((dto.getDtName()).equalsIgnoreCase(documentTypeDTO.getDtName())
					|| (dto.getDtCode()).equalsIgnoreCase(documentTypeDTO
							.getDtCode())) {
				successFlag = false;
				return successFlag;
			} else {
				successFlag = true;
			}
		}

		if (adminDao.saveDocumentType(documentTypeDTO)) {
			bootUpLoader.loadDocTypeMap();
			successFlag = true;
		} else {
			successFlag = false;
		}
		return successFlag;
	}

	public boolean saveDocumentCategory(
			DocumentCategoryForm documentCategoryForm) {

		/*Collection<String> documentCategory = ApplicationMaps.DOCUMENT_CAT_ID_MAP
				.values();
		Collection<Integer> documentType = ApplicationMaps.DOCUMENT_TYPE_ID_NAME_MAP
				.keySet();*/

		boolean existsFlag = true;
		List<DocumentCategoryDTO> docCatList = ApplicationMaps.DOC_TYP_DOC_CAT_MAP.get(documentCategoryForm.getDcParentTypeId());
		if(null!=docCatList){
			for (DocumentCategoryDTO docCategory : docCatList) {
				if(docCategory.getDcName().equals(documentCategoryForm.getDcName())
						|| docCategory.getDcCode().equals(documentCategoryForm.getDcCode())){
					existsFlag = false;
					return existsFlag;
				}
			}
		}
		
		/*for (String docCategory : documentCategory) {
			for (Integer docType : documentType) {
				if (docType.equals((documentCategoryForm.getDcParentTypeId()))) {
					if (docCategory.equalsIgnoreCase(documentCategoryForm
							.getDcName())) {
						successFlag = false;
						return successFlag;
					}
				} else {
					successFlag = true;
				}
			}
		}*/
		
			boolean successFlag = false;
			DocumentCategoryDTO categoryDTO = new DocumentCategoryDTO();
			categoryDTO.setDcName(documentCategoryForm.getDcName());
			categoryDTO.setDcCode(documentCategoryForm.getDcCode());

			DocumentTypeDTO dcParentType = new DocumentTypeDTO();
			dcParentType.setDtId(documentCategoryForm.getDcParentTypeId());
			try {
				adminDao.loadDocumentType(dcParentType);
			} catch (Exception e) {
				logger.error(e.getMessage(),e);
			}
			categoryDTO.setDcParentType(dcParentType);
			if (adminDao.saveDocumentCategory(categoryDTO)) {
				bootUpLoader.loadDocTypeMap();
				successFlag = true;
			} else {
				successFlag = false;
			}
		return successFlag;
	}

	public boolean saveDocumentsubCategory(
			DocumentSubCategory documentSubCategory) {

//		Collection<String> docSubCategory = ApplicationMaps.DOCUMENT_SUB_CAT_ID_MAP
//				.values();
//		Collection<String> documentCategory = ApplicationMaps.DOCUMENT_CAT_ID_MAP
//				.values();

		
		boolean existsFlag = true;
		List<DocumentSubCategory> docSubCatList = ApplicationMaps.DOC_CAT_DOC_SUBCAT_MAP.get(documentSubCategory.getDscParentCategory().getDcId());
		if(null != docSubCatList){
			for (DocumentSubCategory docSubCategory : docSubCatList) {
				if(docSubCategory.getDscCode().equals(documentSubCategory.getDscCode())  
						|| docSubCategory.getDscName().equals(documentSubCategory.getDscName())){
					existsFlag = false;
					return existsFlag;
				}
			}
		}
		
		boolean successFlag = false;


//		for (String string : docSubCategory) {
//			for (String docCategory : documentCategory) {
//				if (string.equalsIgnoreCase(documentSubCategory.getDscName())) {
//					if (docCategory.equalsIgnoreCase(documentSubCategory.getDscParentCategory().getDcName())) {
//						successFlag = false;
//						return successFlag;
//					}
//				} else {
//					successFlag = true;
//				}
//			}
//		}
		if (adminDao.saveDocumentSubCategory(documentSubCategory)) {
			bootUpLoader.loadDocTypeMap();
			successFlag = true;
		} else {
			successFlag = false;
		}
		return successFlag;
	}

	public List<CompanyDetailsDTO> loadAllCompanies() {
		try {
			return commonDao.loadAllCompany();
		} catch (Exception e) {
			// e.printStackTrace();
			logger.error(e.getMessage());
			return null;
		}
	}

	public List<BusinessUnitTypeDTO> loadAllBU() {
		try {
			return commonDao.loadAllBU();
		} catch (Exception e) {
			// e.printStackTrace();
			logger.error(e.getMessage());
			return null;
		}
	}

	public List<DepartmentDetailsDTO> loadallDepartment() {
		try {
			return commonDao.loadAllDepts();
		} catch (Exception e) {
			// e.printStackTrace();
			logger.error(e.getMessage());
			return null;
		}
	}

	public List<UserDetailsDTO> loadAllUsers() {
		List<UserDetailsDTO> usersList = null;
		try {
			usersList = commonDao.loadAllUsers();

		} catch (Exception e) {
			logger.error(e.getMessage());
			if (null == usersList)
				usersList = new ArrayList<UserDetailsDTO>();
		}
		return usersList;
	}

	public UserDetailsDTO getUserForId(String userId) {
		try {
			UserDetailsDTO UserDetailsDTO = adminDao
					.fetchUserDetailsForUserId(userId);
			return adminDao
					.migrateUserauthDetailstoUserDetails(UserDetailsDTO
							.getUsername());
		} catch (Exception e) {
			// e.printStackTrace();
			logger.error(e.getMessage());
			return null;
		}
	}

	public List<RoleDetailsDTO> loadAllRoles() {
		try {
			return commonDao.loadAllRoles();
		} catch (Exception e) {
			// e.printStackTrace();
			logger.error(e.getMessage());
			return null;
		}
	}

	public List<CompanyDetailsDTO> loadAllParentCompanies(
			CompanyDetailsDTO companyDetailsDTO) {

		try {
			DetachedCriteria detachedCriteria = DetachedCriteria
					.forClass(CompanyDetailsDTO.class);
			detachedCriteria.add(Restrictions.eq("child", false));
			List<CompanyDetailsDTO> parentcompanyList = (List<CompanyDetailsDTO>) commonDao
					.loadAllByCriteria(detachedCriteria);
			return parentcompanyList;
		} catch (Throwable e) {
			logger.error(e.getMessage());
			return null;
		}
	}

	public boolean insertDataInMasterDetailsTable(Set<String> dataForWFTable) {

		logger.debug("in service class: " + dataForWFTable);

		boolean successFlag = false;

		Set<String> tempDataOfWFTable = new HashSet<String>();
		tempDataOfWFTable.add("Type");
		tempDataOfWFTable.add("Location");
		tempDataOfWFTable.add("Department");

		logger.debug("tempDataOfWFTable" + tempDataOfWFTable);

		for (String dataToBeInsertedInWFTable : tempDataOfWFTable) {
			MasterDetailsForDMSWFDTO masterDetailsForDMSWFDTO = new MasterDetailsForDMSWFDTO();

			if (dataForWFTable.contains(dataToBeInsertedInWFTable)) {
				logger.debug(dataToBeInsertedInWFTable);
				masterDetailsForDMSWFDTO.setMasterAttribute(attributes
						.valueOf(dataToBeInsertedInWFTable));
				masterDetailsForDMSWFDTO.setMasterAttributeStatus(true);
				successFlag = adminDao
						.insertDetailsInMasterDetailsTable(masterDetailsForDMSWFDTO);
				ApplicationMaps.ARMORY_MASTER_DATA.put(
						masterDetailsForDMSWFDTO.getMasterAttribute(), true);
			} else {
				masterDetailsForDMSWFDTO.setMasterAttribute(attributes
						.valueOf(dataToBeInsertedInWFTable));
				masterDetailsForDMSWFDTO.setMasterAttributeStatus(false);
				successFlag = adminDao
						.insertDetailsInMasterDetailsTable(masterDetailsForDMSWFDTO);
				ApplicationMaps.ARMORY_MASTER_DATA.put(
						masterDetailsForDMSWFDTO.getMasterAttribute(), false);
			}
			logger.debug("VALUE IN TABLE"
					+ masterDetailsForDMSWFDTO.getMasterAttribute());
			logger.debug("VALUE IN TABLE"
					+ masterDetailsForDMSWFDTO.isMasterAttributeStatus());
			logger.debug("VALUE IN MAP" + ApplicationMaps.ARMORY_MASTER_DATA);
			logger.debug("successFlag" + successFlag);
		}

		return successFlag;
	}

	public List loadLocationDetails(LocationMasterDTO locationMasterDTO) {
		return commonDao.loadAll(LocationMasterDTO.class);
	}

	public List<LocationDetailsDTO> loadLocationDetails(
			LocationDetailsDTO locationDetailsDTO) {
		return commonDao.loadAll(LocationDetailsDTO.class);
	}

	public JSONArray loadAllDistrictsAccToState(String state) {
		JSONArray districtArray = new JSONArray();

		List<String> districtList = ApplicationMaps.STATE_DISTRICT_MAP
				.get(state);
		if (null != districtList) {
			HashMap<String, String> districtMap = new HashMap<String, String>();
			Set<String> districtSet = new HashSet<String>();
			for (String districtsAccToState : districtList) {
				districtSet.add(districtsAccToState);
			}
			for (String district : districtSet) {
				districtMap = new HashMap<String, String>();
				districtMap.put("value", state);
				districtMap.put("display", district);
				districtArray.put(districtMap);
			}
		}
		logger.debug("Number of districts loaded for '" + state + "' is: " + districtArray.length());
		return districtArray;
	}

	public JSONArray loadAllCityAccToDistrict(String district) {

		JSONArray cityArray = new JSONArray();

		List<String> cityList = ApplicationMaps.DISTRICT_CITY_MAP
				.get(district);
		if (null != cityList) {
			HashMap<String, String> cityMap = new HashMap<String, String>();
			Set<String> citySet = new HashSet<String>();
			for (String cityAccToDistrict : cityList) {
				citySet.add(cityAccToDistrict);
			}
			for (String city : citySet) {
				cityMap = new HashMap<String, String>();
				cityMap.put("value", district);
				cityMap.put("display", city);
				cityArray.put(cityMap);
			}
		}
		logger.debug("Number of cities loaded for '" + district + "' is: " + cityArray.length());
		return cityArray;
	}

	public boolean saveCompanyEditDetails(CompanyDetailsDTO companyDetailsDTO) {

		boolean successFlag;

		if (adminDao.saveCompanyEditDetails(companyDetailsDTO)) {
			bootUpLoader.loadCompany();
			bootUpLoader.loadBusLocs();
			bootUpLoader.loadDepts();
			bootUpLoader.loadUserMap();
			
			successFlag = true;
		} else {
			successFlag = false;
		}

		logger.debug("successFlag in service" + successFlag);

		return successFlag;
	}

	public boolean saveUnitTypeEditDetails(
			BusinessUnitTypeDTO businessUnitTypeDTO) {

		boolean successFlag;

		if (adminDao.saveUnitType(businessUnitTypeDTO)) {
			bootUpLoader.loadBusLocs();
			successFlag = true;
		} else {
			successFlag = false;
		}

		return successFlag;
	}

	public boolean editUnitTypeDetails(BusinessUnitTypeDTO businessUnitTypeDTO) {
		boolean successFlag;
		if (adminDao.saveUnitTypeEditDetails(businessUnitTypeDTO)) {
			bootUpLoader.loadBusLocs();
			successFlag = true;
		} else {
			successFlag = false;
		}

		return successFlag;
	}

	public boolean saveDepartmentEditDetails(
			DepartmentDetailsDTO departmentDetailsDTO) {
		boolean successFlag;

		if (adminDao.saveDepartmentEditDetails(departmentDetailsDTO)) {
			bootUpLoader.loadDepts();
			successFlag = true;
		} else {
			successFlag = false;
		}

		return successFlag;

	}

	public boolean saveBusinessUnitEditDetails(LocationForm locationForm) {

		LocationDetailsDTO detailsDTO = new LocationDetailsDTO();
		detailsDTO.setLdId(locationForm.getLdId());
		detailsDTO.setLdCode(locationForm.getLdCode());
		detailsDTO.setLdCompanyId(locationForm.getLdCompanyId());
		detailsDTO.setLdName(locationForm.getLdName());
		detailsDTO.setLdType(locationForm.getLdType());
		List<DepartmentDetailsDTO> departmentDetailsDTOs = new ArrayList<DepartmentDetailsDTO>();
		Long[] ddId = locationForm.getDdId();
		for (Long id : ddId) {
			DepartmentDetailsDTO detailsDTO2 = ApplicationMaps.DEPARTMENTID_DEPARTMENT_MAP
					.get(id);
			departmentDetailsDTOs.add(detailsDTO2);
		}
		detailsDTO.setDepartmentDetailsDTOs(departmentDetailsDTOs);

		boolean successFlag;

		if (adminDao.saveBusinessUnitEditDetails(detailsDTO)) {
			bootUpLoader.loadBusLocs();
			successFlag = true;
		} else {
			successFlag = false;
		}
		return successFlag;
	}

	public boolean saveUserDetailsAfterEditing(UserDetailsDTO userDetailsDTO) {
		boolean successFlag;
		userDetailsDTO.setAccountNonExpired(true);
		userDetailsDTO.setAccountNonLocked(true);
		userDetailsDTO.setCredentialsNonExpired(true);
		userDetailsDTO.setEnabled(true);

		Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
		String[] roles = userDetailsDTO.getRole();
		if (null != roles && roles.length > 0) {
			for (String role : roles) {
				RoleDetailsDTO detailsDTO2 = new RoleDetailsDTO();
				detailsDTO2.setAuthority(role);

				authorities.add(detailsDTO2);
			}
		}
		logger.debug(authorities);
		userDetailsDTO.setAuthorities(authorities);

		if (adminDao.saveEditedUSerDetails(userDetailsDTO)) {
			bootUpLoader.loadUserGroupMap();
			successFlag = true;
		} else {
			successFlag = false;
		}
		return successFlag;
	}

	public boolean updateTypeDetails(DocumentTypeDTO documentTypeDTO) {

		boolean successFlag;

		if (adminDao.updateTypeDetails(documentTypeDTO)) {
			bootUpLoader.loadDocTypeMap();
			successFlag = true;
		} else {
			successFlag = false;
		}

		return successFlag;
	}

	public boolean updateDocCategoryDetails(
			DocumentCategoryDTO documentCategoryDTO) {
		boolean successFlag;

		if (adminDao.updateCategoryDetails(documentCategoryDTO)) {

			bootUpLoader.loadDocTypeMap();
			successFlag = true;
		} else {

			successFlag = false;
		}
		return successFlag;
	}

	public boolean saveDocSubCategoryNewDetails(
			DocumentSubCategory documentSubCategory) {
		boolean successFlag;

		if (adminDao.updateDocSubCategDetails(documentSubCategory)) {
			bootUpLoader.loadDocumentDetail();
			bootUpLoader.loadDocTypeMap();
			successFlag = true;
		} else {
			successFlag = false;
		}

		return successFlag;
	}

	public boolean deleteCompany(CompanyDetailsDTO companyDetailsDTO) {
		boolean successFlag;

		if (adminDao.deleteSelectedCompany(companyDetailsDTO)) {
			bootUpLoader.loadCompany();
			successFlag = true;
		} else {
			successFlag = false;
		}

		return successFlag;
	}

	public List<UserRoleMappingDTO> fetchUserForRoles(String roleId) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(UserRoleMappingDTO.class);
		detachedCriteria.add(Restrictions.eq("roleId", roleId));
		return adminDao.usersListForRoleId(detachedCriteria);
	}

	public boolean saveSuperFicialRoleMappingDetail(
			SuperFicialRolesMappingForm superFicialRolesMappingForm) {

		boolean resultOfSave = false;
		List<SuperficialRolesMapping> listOfRoleMappingObjects = new ArrayList<SuperficialRolesMapping>();
		for (long locId : superFicialRolesMappingForm.getLdId()) {
			SuperficialRolesMapping superficialRolesMapping = new SuperficialRolesMapping();
			superficialRolesMapping.setCdId(superFicialRolesMappingForm
					.getCdId());
			superficialRolesMapping.setLdId(locId);
			superficialRolesMapping.setRoleId(superFicialRolesMappingForm
					.getRoleId());
			superficialRolesMapping.setUserId(superFicialRolesMappingForm
					.getUserId());
			listOfRoleMappingObjects.add(superficialRolesMapping);
		}

		if (adminDao.saveSuperficialMappingDetails(listOfRoleMappingObjects)) {
			bootUpLoader.loadSuperficialRoleMappingData();
			resultOfSave = true;
		}

		return resultOfSave;
	}

	public boolean deletePreviousDataForSuperficialRoleMapping(String userName,
			String roleId) {

		boolean resultOfDelete = false;

		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(SuperficialRolesMapping.class);

		if (null != userName)
			detachedCriteria.add(Restrictions.eq("userId", userName));
		if (null != roleId)
			detachedCriteria.add(Restrictions.eq("roleId", roleId));

		List<SuperficialRolesMapping> mappings = adminDao
				.fetchDataForSuperFicialRoleMapping(detachedCriteria);
		if (null != mappings && mappings.size() > 0) {
			for (SuperficialRolesMapping superficialRolesMapping : mappings) {
				resultOfDelete = adminDao
						.deleteDataForSuperFicialRoleMapping(superficialRolesMapping);
			}
		}

		return resultOfDelete;
	}

	public List getOpenDocsForUsers(UserDetailsDTO UserDetailsDTO) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(DocumentWorkflowDetailsDTO.class);

		UserDetailsDTO requestDTO = adminDao
				.migrateUserauthDetailstoUserDetails(UserDetailsDTO
						.getUsername());

		detachedCriteria.add(Restrictions.eq("wfAssignedUser",
				requestDTO.getUsername()));
		detachedCriteria.add(Restrictions.eq("wfEventStatus",
				WorkflowEventStatus.OPEN));

		return commonDao.loadAllByCriteria(detachedCriteria);

	}

	public List getDocGeneralDetails(
			DocumentWorkflowDetailsDTO documentWorkflowDetailsDTO) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(DocGeneralDetailsDTO.class);

		detachedCriteria.add(Restrictions.eq("docId",
				documentWorkflowDetailsDTO.getDocId()));
		return commonDao.loadAllByCriteria(detachedCriteria);
	}

	public List<DocGeneralDetailsDTO> getDocumentForDocCode(String docCode) {
		return adminDao.loadDocument(docCode);
	}

	public DocGeneralDetailsDTO getDocumentForDocId(long docId) {
		return adminDao.loadDocumentForId(docId);
	}
	
	public UserDetailsDTO loadUserForUsername(String userId) {

		UserDetailsDTO detailsDTO = new UserDetailsDTO();
		try {
			UserDetailsDTO detailsAuthDTO = adminDao
					.fetchUserDetailsForUserId(userId);
			return adminDao.migrateUserauthDetailstoUserDetails(detailsAuthDTO
					.getUsername());
			// detailsDTO = (UserDetailsDTO)
			// adminDao.fetchUserDetailsForUserId(userId);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (detailsDTO != null) {
			Collection<GrantedAuthority> authorities = detailsDTO
					.getAuthorities();
			String[] roles = new String[authorities.size()];
			for (GrantedAuthority grantedAuthority : authorities) {
				int i = 0;
				RoleDetailsDTO roleDetailsDTO = (RoleDetailsDTO) grantedAuthority;
				roles[i] = ApplicationMaps.ROLEID_ROLENAME_MAP
						.get(roleDetailsDTO.getRoleId());
			}
			detailsDTO.setRole(roles);

		}

		return detailsDTO;
	}

	public void updateUserFirst(UserDetailsDTO detailsDTO) {
		adminDao.updateNewUserDetails(detailsDTO);
	}

	public void reloadCache() {
		bootUpLoader.bootUp();
	}

}
